<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="80px">
      <el-form-item label="房源标题" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入房源标题"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="房东ID" prop="ownerId">
        <el-input
          v-model="queryParams.ownerId"
          placeholder="请输入房东ID"
          clearable
          @keyup.enter="handleQuery"
          type="number"
        />
      </el-form-item>
      <el-form-item label="租金" prop="price">
        <el-input
          v-model="queryParams.price"
          placeholder="请输入租金"
          clearable
          @keyup.enter="handleQuery"
          type="number"
        />
      </el-form-item>
      <el-form-item label="押金" prop="deposit">
        <el-input
          v-model="queryParams.deposit"
          placeholder="请输入押金"
          clearable
          @keyup.enter="handleQuery"
          type="number"
        />
      </el-form-item>
      <el-form-item label="出售状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择出售状态" clearable>
          <el-option
            v-for="dict in sys_house_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="房源状态" prop="delFlag">
        <el-select v-model="queryParams.delFlag" placeholder="请选择房源标记" clearable>
          <el-option
            v-for="dict in sys_house_flag"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="更新时间" style="width: 308px">
        <el-date-picker
          v-model="daterangeUpdateTime"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['system:house:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:house:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:house:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['system:house:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <el-table show-overflow-tooltip v-loading="loading" :data="houseList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" prop="count" />
      <el-table-column label="房屋预览" align="center" prop="image">
        <template #default="scope">
          <el-image
              class="houseImage"
              preview-teleported
              hide-on-click-modal
              infinite
              :preview-src-list="scope.row.image.split(',').map(v=>'http://localhost:3000' + v)"
              :src="'http://localhost:3000'+ scope.row.image.split(',')[0]"
              lazy
          />
        </template>
      </el-table-column>
      <el-table-column label="房源标题" align="center" prop="title" />
      <el-table-column label="房东" align="center" prop="ownerName" />
      <el-table-column label="租金" align="center" prop="price" />
      <el-table-column label="押金" align="center" prop="deposit" />
      <el-table-column label="出售状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="sys_house_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="房源标记" align="center" prop="delFlag">
        <template #default="scope">
          <dict-tag :options="sys_house_flag" :value="scope.row.delFlag"/>
        </template>
      </el-table-column>
      <el-table-column label="更新时间" align="center" prop="updateTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.updateTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="房源地址" align="center" prop="address" />
      <el-table-column label="房源描述" align="center" prop="description" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:house:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['system:house:remove']">删除</el-button>
          <el-button
              link
              type="primary"
              icon="Delete"
              :disabled="scope.row.status === '0' || scope.row.delFlag === '0'"
              @click="handlePurchase(scope.row)"
              v-hasPermi="['system:house:purchase']"
          >购买</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
    <!-- 添加或修改房源表对话框 -->
    <el-dialog :title="title" v-model="open" width="clamp(350px,90%,600px)" append-to-body>
      <el-form ref="houseRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="房源标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入房源标题" />
        </el-form-item>
        <el-form-item label="租金" prop="price">
          <el-input-number v-model="form.price" placeholder="请输入租金" />
        </el-form-item>
        <el-form-item label="押金" prop="deposit">
          <el-input-number v-model="form.deposit" placeholder="请输入押金" />
        </el-form-item>
        <el-form-item label="房源地址" prop="address">
          <el-cascader
              size="large"
              :options="regionData"
              v-model="form.address">
          </el-cascader>
<!--          <el-input v-model="form.address" type="textarea" placeholder="请输入内容" />-->
        </el-form-item>
        <el-form-item label="房源描述" prop="description">
          <el-input :minlength="5" :maxlength="50" v-model="form.description" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="选择图片" prop="image">
          <el-upload
              v-model:file-list="fileList"
              class="upload-demo"
              :limit="9"
              :before-upload="handleBeforeUpload"
              :http-request="handleUploads"
              accept=".jpg, .png, .JPG, .PNG, .jpeg, .JPEG"
              ref="uploadBanner"
              multiple
          >
            <el-button :icon="Plus" type="primary">点击选择</el-button>
            <template #tip>
              <div class="el-upload__tip">
                jpg/png files with a size less than 500KB.
              </div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog title="提交订单" v-model="orderDialog" width="clamp(350px,90%,600px)" append-to-body>
      <el-descriptions style="margin-left: 20px;">
        <el-descriptions-item label="标题">{{ curHouse.title }}</el-descriptions-item>
        <el-descriptions-item label="地址">{{ curHouse.address }}</el-descriptions-item>
        <el-descriptions-item label="房东">{{ curHouse.owner.userName }}</el-descriptions-item>
        <el-descriptions-item label="租金">
          <el-statistic :value-style="{ fontSize: '14px' }" :precision="2" :value="curHouse.price" />
        </el-descriptions-item>
        <el-descriptions-item label="押金">
          <el-statistic :value-style="{ fontSize: '14px' }" :precision="2" :value="curHouse.deposit" />
        </el-descriptions-item>
        <el-descriptions-item label="总计">
          <el-statistic :value-style="{ fontSize: '15px', color: 'red' }" :precision="2" :value="+curHouse.price + +curHouse.deposit" />
        </el-descriptions-item>
      </el-descriptions>
      <el-form ref="orderRef" :model="orderForm" :rules="orderRules" label-width="100px">
        <el-form-item label="开始日期" prop="startDate">
          <el-date-picker v-model="orderForm.startDate"
                          clearable
                          placeholder="请选择开始日期"
                          type="datetime"
                          value-format="YYYY-MM-DD HH:mm:ss">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="结束日期" prop="endDate">
          <el-date-picker v-model="orderForm.endDate"
                          clearable
                          placeholder="请选择结束日期"
                          type="datetime"
                          value-format="YYYY-MM-DD HH:mm:ss">
          </el-date-picker>
        </el-form-item>

      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitOrder">确 定</el-button>
          <el-button @click="orderCancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script setup name="House">
import {addHouse, delHouse, getHouse, HousePurchase, listHouse, updateHouse} from "@/api/system/house";
import {codeToText, regionData} from 'element-china-area-data'
import dayjs from 'dayjs';

import {ElMessage} from "element-plus";
import {uploads} from "@/api/tool/gen.js";
import {Plus} from "@element-plus/icons-vue";

const fileList = ref([])
const { proxy } = getCurrentInstance();
const { sys_house_status,sys_house_flag } = proxy.useDict("sys_house_status","sys_house_flag");
const houseList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const daterangeUpdateTime = ref([]);
const daterangeCreateTime = ref([]);
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    title: null,
    price: null,
    deposit: null,
    status: null,
    delFlag: null,
    updateTime: null,
  },
  rules: {
    title: [
      { required: true, message: "房源标题不能为空", trigger: "blur" }
    ],
    ownerId: [
      { required: true, message: "房东ID不能为空", trigger: "blur" }
    ],
    price: [
      { required: true, message: "租金不能为空", trigger: "blur" }
    ],
    deposit: [
      { required: true, message: "押金不能为空", trigger: "blur" }
    ],
    image: [
      { required: true, message: '房源图片不能为空', trigger: "blur" }
    ]
  }
});
const { queryParams, form, rules } = toRefs(data);
const isAdd = ref(true)
const handleBeforeUpload = (rawFile) => {
  const isValidSize = rawFile.size / 1024 / 1024 < 5;
  if(!isValidSize){
    ElMessage.error('文件大小不能超过 5MB')
    return false
  }
  return true
};
const uploading = ref(false)
const orderDialog = ref(false)
const validateStartDate = (_, value, callback) => {
  const now = dayjs();
  if (!value || dayjs(value).isBefore(now, 'minute')) {
    callback(new Error('开始时间不能小于当前时间'));
  } else {
    callback(); // 验证通过
  }
};
const validateEndDate = (_, value, callback) => {
  // 获取开始时间
  const startDate = orderForm.value.startDate;
  if (!value) {
    callback(new Error('结束时间不能为空'));
  } else if (startDate && dayjs(value).isBefore(dayjs(startDate).add(1, 'month'), 'minute')) {
    callback(new Error('结束时间必须大于开始时间一个月'));
  } else {
    callback();
  }
}

const orderData = reactive({
  orderForm: {},
  orderRules: {
    startDate: [
      {required: true, message: "开始时间不能为空", trigger: "blur"},
      { validator: validateStartDate, trigger: "blur" }
    ],
    endDate: [
      {required: true, message: "开始时间不能为空", trigger: "blur"},
      { validator: validateEndDate, trigger: "blur" }
    ]
  },
  curHouse: {}
})
const { orderForm, orderRules, curHouse } = toRefs(orderData);


const handleUploads = async () => {
  if(uploading.value) return
  uploading.value = true
  const formData = new FormData();
  for (const file of fileList.value) formData.append('files', file.raw);
  const response = await uploads(formData);
  if(response.code === 200) form.value.image = [...form.value.image, ...response.data.map(v=>'/v1' + v.url)];
  uploading.value = false
};

const orderReset = () => {
  orderForm.value = {
    startDate: null,
    endDate: null,
    houseId: null,
    landlord: null
  };
  curHouse.value = {}
  proxy.resetForm("orderRef");
}

const orderCancel = () => {
  orderDialog.value = false;
  orderReset()
}

/** 查询房源表列表 */
async function getList() {
  loading.value = true;
  queryParams.value.params = {};
  if (null != daterangeUpdateTime && '' != daterangeUpdateTime) {
    queryParams.value.params["beginUpdateTime"] = daterangeUpdateTime.value[0];
    queryParams.value.params["endUpdateTime"] = daterangeUpdateTime.value[1];
  }
  if (null != daterangeCreateTime && '' != daterangeCreateTime) {
    queryParams.value.params["beginCreateTime"] = daterangeCreateTime.value[0];
    queryParams.value.params["endCreateTime"] = daterangeCreateTime.value[1];
  }
  const response = await listHouse(queryParams.value)
  houseList.value = response.rows.map((v, i)=>({ ...v, ownerName: v.owner.userName, address: v.address.split('/').map(v=>codeToText[v]).join('/'), count: (queryParams.value.pageNum - 1) * queryParams.value.pageSize + (i + 1) }));
  total.value = response.total;
  loading.value = false;
}
// 取消按钮
function cancel() {
  open.value = false;
  reset();
}
// 表单重置
function reset() {
  form.value = {
    id: null,
    title: null,
    price: 0,
    deposit: 0,
    status: null,
    delFlag: null,
    updateTime: null,
    createTime: null,
    address: [],
    description: null,
    image: []
  };
  fileList.value = []
  proxy.resetForm("houseRef");
}
/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}
/** 重置按钮操作 */
function resetQuery() {
  daterangeUpdateTime.value = [];
  daterangeCreateTime.value = [];
  proxy.resetForm("queryRef");
  handleQuery();
}
// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}
/** 新增按钮操作 */
function handleAdd() {
  reset();
  isAdd.value = true
  form.value.status = '1'
  form.value.delFlag = '1'
  open.value = true;
  title.value = "添加房源";
}
/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  isAdd.value = false
  const _id = row.id || ids.value
  getHouse(_id).then(response => {
    response.data.address = response.data.address.split('/')
    response.data.image = response.data.image.split(',')
    form.value = response.data;
    open.value = true;
    title.value = "修改房源";
  });
}
/** 提交按钮 */
function submitForm() {
  proxy.$refs["houseRef"].validate(valid => {
    if (valid) {
      form.value.address = form.value.address.join('/')
      form.value.image = form.value.image.join(',')
      if (form.value.id != null) {
        updateHouse(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addHouse(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}
/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除房源编号为"' + _ids + '"的数据项？').then(function() {
    return delHouse(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}
/** 导出按钮操作 */
function handleExport() {
  proxy.download('system/house/export', {
    ...queryParams.value
  }, `house_${new Date().getTime()}.xlsx`)
}
/** 购买房源 */
async function handlePurchase(row){
  await getList()
  const _ids = row.id;
  console.log(row);
  curHouse.value = houseList.value.find(v=>v.id===_ids);
  const whether = houseList.value.find(item => item.id === _ids).status === '0'
  if (whether) {
    proxy.$modal.msgWarning('该房源已出售 不可购买！');
  } else {
    const date = new Date();
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');
    const seconds = String(date.getSeconds()).padStart(2, '0');
    orderForm.value.startDate = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
    orderForm.value.houseId = _ids;
    orderForm.value.landlord = row.ownerId
    orderDialog.value = true;
  }
}

async function submitOrder(){
  proxy.$refs["orderRef"].validate(valid => {
    if (valid) {
      HousePurchase(orderForm.value).then(response => {
        if(response.code<=200) proxy.$modal.msgSuccess(response.msg)
        else proxy.$modal.msgError(response.msg)
        orderDialog.value = false
        orderReset()
        getList()
      })
    }
  });
}
getList();

</script>
<style lang="scss" scoped>
.houseImage{
  width: 70px;
  height: 70px;
  transition: all 0.3s ease-in-out 0s
}
.houseImage:hover{
 transform: scale(1.2);
}
</style>


